<!DOCTYPE html>





<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="generator" content="Hexo 3.9.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.3.0">
  <link rel="mask-icon" href="/images/apple-touch-icon-next.png?v=7.3.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.3.0">


<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/font-awesome@4/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.3.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    back2top: {"enable":true,"sidebar":true,"scrollpercent":true},
    save_scroll: false,
    copycode: {"enable":true,"show_result":true,"style":null},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: 'Copy',
      copy_success: 'Copied',
      copy_failure: 'Copy failed'
    }
  };
</script>

  <meta name="description" content="工作中经常会用到 nginx 服务,记录下常用的 nginx 配置">
<meta name="keywords" content="nginx,配置">
<meta property="og:type" content="article">
<meta property="og:title" content="nginx配置location总结及rewrite规则写法[转载]">
<meta property="og:url" content="https://dctxf.com/nginx-regex.html">
<meta property="og:site_name" content="门口摔倒的老大爷">
<meta property="og:description" content="工作中经常会用到 nginx 服务,记录下常用的 nginx 配置">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-03-21T06:05:52.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="nginx配置location总结及rewrite规则写法[转载]">
<meta name="twitter:description" content="工作中经常会用到 nginx 服务,记录下常用的 nginx 配置">
  <link rel="alternate" href="/rss.xml" title="门口摔倒的老大爷" type="application/atom+xml">
  <link rel="canonical" href="https://dctxf.com/nginx-regex">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>nginx配置location总结及rewrite规则写法[转载] | 门口摔倒的老大爷</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9ef591dac562902e43858b296afe9979";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>






  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  <div class="container sidebar-position-left">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">门口摔倒的老大爷</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>Home</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    
      
    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>About</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>Tags<span class="badge">39</span></a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>Categories<span class="badge">5</span></a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>Archives<span class="badge">57</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>Search</a>
      </li>
    
  </ul>

    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>


    </div>
</nav>
</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content page-post-detail">
            

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://dctxf.com/nginx-regex.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="dctxf">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/logo.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="门口摔倒的老大爷">
    </span>
      <header class="post-header">

        
          <h2 class="post-title" itemprop="name headline">nginx配置location总结及rewrite规则写法[转载]

            
          </h2>
        

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              
                
              

              <time title="Created: 2018-03-14 15:52:19" itemprop="dateCreated datePublished" datetime="2018-03-14T15:52:19+08:00">2018-03-14</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2018-03-21 14:05:52" itemprop="dateModified" datetime="2018-03-21T14:05:52+08:00">2018-03-21</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/code/" itemprop="url" rel="index"><span itemprop="name">code</span></a></span>

                
                
              
            </span>
          

          
            
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
        
      
      <span class="post-meta-item-text">Disqus: </span>
    
    <a title="disqus" href="/nginx-regex.html#comments" itemprop="discussionUrl">
      <span class="post-comments-count disqus-comment-count" data-disqus-identifier="nginx-regex.html" itemprop="commentCount"></span>
    </a>
  </span>
  
  
          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>工作中经常会用到 nginx 服务,记录下常用的 nginx 配置</p>
<a id="more"></a>

<h2 id="1-location-正则写法"><a href="#1-location-正则写法" class="headerlink" title="1. location 正则写法"></a>1. location 正则写法</h2><p>一个示例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">location  = / &#123;</span><br><span class="line">  # 精确匹配 / ，主机名后面不能带任何字符串</span><br><span class="line">  [ configuration A ]</span><br><span class="line">&#125;</span><br><span class="line">location  / &#123;</span><br><span class="line">  # 因为所有的地址都以 / 开头，所以这条规则将匹配到所有请求</span><br><span class="line">  # 但是正则和最长字符串会优先匹配</span><br><span class="line">  [ configuration B ]</span><br><span class="line">&#125;</span><br><span class="line">location /documents/ &#123;</span><br><span class="line">  # 匹配任何以 /documents/ 开头的地址，匹配符合以后，还要继续往下搜索</span><br><span class="line">  # 只有后面的正则表达式没有匹配到时，这一条才会采用这一条</span><br><span class="line">  [ configuration C ]</span><br><span class="line">&#125;</span><br><span class="line">location ~ /documents/Abc &#123;</span><br><span class="line">  # 匹配任何以 /documents/Abc 开头的地址，匹配符合以后，还要继续往下搜索</span><br><span class="line">  # 只有后面的正则表达式没有匹配到时，这一条才会采用这一条</span><br><span class="line">  [ configuration CC ]</span><br><span class="line">&#125;</span><br><span class="line">location ^~ /images/ &#123;</span><br><span class="line">  # 匹配任何以 /images/ 开头的地址，匹配符合以后，停止往下搜索正则，采用这一条。</span><br><span class="line">  [ configuration D ]</span><br><span class="line">&#125;</span><br><span class="line">location ~* \.(gif|jpg|jpeg)$ &#123;</span><br><span class="line">  # 匹配所有以 gif,jpg或jpeg 结尾的请求</span><br><span class="line">  # 然而，所有请求 /images/ 下的图片会被 config D 处理，因为 ^~ 到达不了这一条正则</span><br><span class="line">  [ configuration E ]</span><br><span class="line">&#125;</span><br><span class="line">location /images/ &#123;</span><br><span class="line">  # 字符匹配到 /images/，继续往下，会发现 ^~ 存在</span><br><span class="line">  [ configuration F ]</span><br><span class="line">&#125;</span><br><span class="line">location /images/abc &#123;</span><br><span class="line">  # 最长字符匹配到 /images/abc，继续往下，会发现 ^~ 存在</span><br><span class="line">  # F与G的放置顺序是没有关系的</span><br><span class="line">  [ configuration G ]</span><br><span class="line">&#125;</span><br><span class="line">location ~ /images/abc/ &#123;</span><br><span class="line">  # 只有去掉 config D 才有效：先最长匹配 config G 开头的地址，继续往下搜索，匹配到这一条正则，采用</span><br><span class="line">    [ configuration H ]</span><br><span class="line">&#125;</span><br><span class="line">location ~* /js/.*/\.js</span><br></pre></td></tr></table></figure>

<ul>
<li>已=开头表示精确匹配</li>
<li>如 A 中只匹配根目录结尾的请求，后面不能带任何字符串。</li>
<li>^~ 开头表示 uri 以某个常规字符串开头，不是正则匹配</li>
<li>~ 开头表示区分大小写的正则匹配;</li>
<li>~* 开头表示不区分大小写的正则匹配</li>
<li>/ 通用匹配, 如果没有其它匹配,任何请求都会匹配到</li>
</ul>
<p>顺序 no 优先级：<br>(location =) &gt; (location 完整路径) &gt; (location ^~ 路径) &gt; (location <del>,</del>* 正则顺序) &gt; (location 部分起始路径) &gt; (/)</p>
<p>上面的匹配结果<br>按照上面的 location 写法，以下的匹配示例成立：</p>
<ul>
<li><code>/ -&gt; config A</code><br>精确完全匹配，即使/index.html 也匹配不了</li>
<li><code>/downloads/download.html -&gt; config B</code><br>匹配 B 以后，往下没有任何匹配，采用 B</li>
<li><code>/images/1.gif -&gt; configuration D</code><br>匹配到 F，往下匹配到 D，停止往下</li>
<li><code>/images/abc/def -&gt; config D</code><br>最长匹配到 G，往下匹配 D，停止往下<br>你可以看到 任何以/images/开头的都会匹配到 D 并停止，FG 写在这里是没有任何意义的，H 是永远轮不到的，这里只是为了说明匹配顺序</li>
<li><code>/documents/document.html -&gt; config C</code><br>匹配到 C，往下没有任何匹配，采用 C</li>
<li><code>/documents/1.jpg -&gt; configuration E</code><br>匹配到 C，往下正则匹配到 E</li>
<li><code>/documents/Abc.jpg -&gt; config CC</code><br>最长匹配到 C，往下正则顺序匹配到 CC，不会往下到 E</li>
</ul>
<h3 id="实际使用建议"><a href="#实际使用建议" class="headerlink" title="实际使用建议"></a>实际使用建议</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">所以实际使用中，个人觉得至少有三个匹配规则定义，如下：</span><br><span class="line">#直接匹配网站根，通过域名访问网站首页比较频繁，使用这个会加速处理，官网如是说。</span><br><span class="line">#这里是直接转发给后端应用服务器了，也可以是一个静态首页</span><br><span class="line"># 第一个必选规则</span><br><span class="line">location = / &#123;</span><br><span class="line">    proxy_pass http://tomcat:8080/index</span><br><span class="line">&#125;</span><br><span class="line"># 第二个必选规则是处理静态文件请求，这是nginx作为http服务器的强项</span><br><span class="line"># 有两种配置模式，目录匹配或后缀匹配,任选其一或搭配使用</span><br><span class="line">location ^~ /static/ &#123;</span><br><span class="line">    root /webroot/static/;</span><br><span class="line">&#125;</span><br><span class="line">location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ &#123;</span><br><span class="line">    root /webroot/res/;</span><br><span class="line">&#125;</span><br><span class="line">#第三个规则就是通用规则，用来转发动态请求到后端应用服务器</span><br><span class="line">#非静态文件请求就默认是动态请求，自己根据实际把握</span><br><span class="line">#毕竟目前的一些框架的流行，带.php,.jsp后缀的情况很少了</span><br><span class="line">location / &#123;</span><br><span class="line">    proxy_pass http://tomcat:8080/</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a href="http://tengine.taobao.org/book/chapter_02.html" target="_blank" rel="noopener">http://tengine.taobao.org/book/chapter_02.html</a><br><a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html" target="_blank" rel="noopener">http://nginx.org/en/docs/http/ngx_http_rewrite_module.html</a></p>
<h2 id="2-Rewrite-规则"><a href="#2-Rewrite-规则" class="headerlink" title="2. Rewrite 规则"></a>2. Rewrite 规则</h2><p>rewrite 功能就是，使用 nginx 提供的全局变量或自己设置的变量，结合正则表达式和标志位实现 url 重写以及重定向。rewrite 只能放在 server{},location{},if{}中，并且只能对域名后边的除去传递的参数外的字符串起作用，例如 <code>http://seanlook.com/a/we/index.php?id=1&amp;u=str</code> 只对<code>/a/we/index.php</code>重写。语法<code>rewrite regex replacement [flag]</code>;</p>
<p>如果相对域名或参数字符串起作用，可以使用全局变量匹配，也可以使用 proxy_pass 反向代理。</p>
<p>表明看 rewrite 和 location 功能有点像，都能实现跳转，主要区别在于 rewrite 是在同一域名内更改获取资源的路径，而 location 是对一类路径做控制访问或反向代理，可以 proxy_pass 到其他机器。很多情况下 rewrite 也会写在 location 里，它们的执行顺序是：</p>
<ul>
<li>执行 server 块的 rewrite 指令</li>
<li>执行 location 匹配</li>
<li>执行选定的 location 中的 rewrite 指令</li>
</ul>
<p>如果其中某步 URI 被重写，则重新循环执行 1-3，直到找到真实存在的文件；循环超过 10 次，则返回 500 Internal Server Error 错误。</p>
<h3 id="2-1-flag-标志位"><a href="#2-1-flag-标志位" class="headerlink" title="2.1 flag 标志位"></a>2.1 flag 标志位</h3><ul>
<li><code>last</code> : 相当于 Apache 的[L]标记，表示完成 rewrite</li>
<li><code>break</code> : 停止执行当前虚拟主机的后续 rewrite 指令集</li>
<li><code>redirect</code> : 返回 302 临时重定向，地址栏会显示跳转后的地址</li>
<li><code>permanent</code> : 返回 301 永久重定向，地址栏会显示跳转后的地址</li>
</ul>
<p>因为 301 和 302 不能简单的只返回状态码，还必须有重定向的 URL，这就是 return 指令无法返回 301,302 的原因了。这里 last 和 break 区别有点难以理解：</p>
<ul>
<li>last 一般写在 server 和 if 中，而 break 一般使用在 location 中</li>
<li>last 不终止重写后的 url 匹配，即新的 url 会再从 server 走一遍匹配流程，而 break 终止重写后的匹配</li>
<li>break 和 last 都能组织继续执行后面的 rewrite 指令</li>
</ul>
<h3 id="2-2-if-指令与全局变量"><a href="#2-2-if-指令与全局变量" class="headerlink" title="2.2 if 指令与全局变量"></a>2.2 if 指令与全局变量</h3><h4 id="if-判断指令"><a href="#if-判断指令" class="headerlink" title="if 判断指令"></a>if 判断指令</h4><p>语法为<code>if(condition){...}</code>，对给定的条件 condition 进行判断。如果为真，大括号内的 rewrite 指令将被执行，if 条件(conditon)可以是如下任何内容：</p>
<ul>
<li>当表达式只是一个变量时，如果值为空或任何以 0 开头的字符串都会当做 false</li>
<li>直接比较变量和内容时，使用=或!=</li>
<li><del>正则表达式匹配，</del>*不区分大小写的匹配，!~区分大小写的不匹配</li>
</ul>
<p><code>-f</code>和<code>!-f</code>用来判断是否存在文件<br><code>-d</code>和<code>!-d</code>用来判断是否存在目录<br><code>-e</code>和<code>!-e</code>用来判断是否存在文件或目录<br><code>-x</code>和<code>!-x</code>用来判断文件是否可执行</p>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">if ($http_user_agent ~ MSIE) &#123;</span><br><span class="line">    rewrite ^(.*)$ /msie/$1 break;</span><br><span class="line">&#125; //如果UA包含&quot;MSIE&quot;，rewrite请求到/msid/目录下</span><br><span class="line">if ($http_cookie ~* &quot;id=([^;]+)(?:;|$)&quot;) &#123;</span><br><span class="line">    set $id $1;</span><br><span class="line"> &#125; //如果cookie匹配正则，设置变量$id等于正则引用部分</span><br><span class="line">if ($request_method = POST) &#123;</span><br><span class="line">    return 405;</span><br><span class="line">&#125; //如果提交方法为POST，则返回状态405（Method not allowed）。return不能返回301,302</span><br><span class="line">if ($slow) &#123;</span><br><span class="line">    limit_rate 10k;</span><br><span class="line">&#125; //限速，$slow可以通过 set 指令设置</span><br><span class="line">if (!-f $request_filename)&#123;</span><br><span class="line">    break;</span><br><span class="line">    proxy_pass  http://127.0.0.1;</span><br><span class="line">&#125; //如果请求的文件名不存在，则反向代理到localhost 。这里的break也是停止rewrite检查</span><br><span class="line">if ($args ~ post=140)&#123;</span><br><span class="line">    rewrite ^ http://example.com/ permanent;</span><br><span class="line">&#125; //如果query string中包含&quot;post=140&quot;，永久重定向到example.com</span><br><span class="line">location ~* \.(gif|jpg|png|swf|flv)$ &#123;</span><br><span class="line">    valid_referers none blocked www.jefflei.com www.leizhenfang.com;</span><br><span class="line">    if ($invalid_referer) &#123;</span><br><span class="line">        return 404;</span><br><span class="line">    &#125; //防盗链</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>全局变量<br>下面是可以用作 if 判断的全局变量</p>
<ul>
<li><code>$args</code>： #这个变量等于请求行中的参数，同$query_string</li>
<li><code>$content_length</code> ： 请求头中的 Content-length 字段。</li>
<li><code>$content_type</code> ： 请求头中的 Content-Type 字段。</li>
<li><code>$document_root</code> ： 当前请求在 root 指令中指定的值。</li>
<li><code>$host</code> ： 请求主机头字段，否则为服务器名称。</li>
<li><code>$http_user_agent</code> ： 客户端 agent 信息</li>
<li><code>$http_cookie</code> ： 客户端 cookie 信息</li>
<li><code>$limit_rate</code> ： 这个变量可以限制连接速率。</li>
<li><code>$request_method</code> ： 客户端请求的动作，通常为 GET 或 POST。</li>
<li><code>$remote_addr</code>： 客户端的 IP 地址。</li>
<li><code>$remote_port</code> ： 客户端的端口。</li>
<li><code>$remote_user</code> ： 已经经过 Auth Basic Module 验证的用户名。</li>
<li><code>$request_filename</code> ： 当前请求的文件路径，由 root 或 alias 指令与 URI 请求生成。</li>
<li><code>$scheme</code> ： HTTP 方法（如 http，https）。</li>
<li><code>$server_protocol</code> ： 请求使用的协议，通常是 HTTP/1.0 或 HTTP/1.1。</li>
<li><code>$server_addr</code> ： 服务器地址，在完成一次系统调用后可以确定这个值。</li>
<li><code>$server_name</code> ： 服务器名称。</li>
<li><code>$server_port</code> ： 请求到达服务器的端口号。</li>
<li><code>$request_uri</code> ： 包含请求参数的原始 URI，不包含主机名，如：”/foo/bar.php?arg=baz”。</li>
<li><code>$uri</code> ： 不带请求参数的当前 URI，$uri 不包含主机名，如”/foo/bar.html”。</li>
<li><code>$document_uri</code> ： 与$uri 相同。</li>
</ul>
<p>例：<a href="http://localhost:88/test1/test2/test.php" target="_blank" rel="noopener">http://localhost:88/test1/test2/test.php</a></p>
<ul>
<li><code>$host</code>：localhost</li>
<li><code>$server_port</code>：88</li>
<li><code>$request_uri</code>：<a href="http://localhost:88/test1/test2/test.php" target="_blank" rel="noopener">http://localhost:88/test1/test2/test.php</a></li>
<li><code>$document_uri</code>：/test1/test2/test.php</li>
<li><code>$document_root</code>：/var/www/html</li>
<li><code>$request_filename</code>：/var/www/html/test1/test2/test.php</li>
</ul>
<h3 id="2-3-常用正则"><a href="#2-3-常用正则" class="headerlink" title="2.3 常用正则"></a>2.3 常用正则</h3><ul>
<li>. ： 匹配除换行符以外的任意字符</li>
<li>? ： 重复 0 次或 1 次</li>
<li><ul>
<li>： 重复 1 次或更多次</li>
</ul>
</li>
<li><ul>
<li>： 重复 0 次或更多次</li>
</ul>
</li>
<li>\d ：匹配数字</li>
<li>^ ： 匹配字符串的开始</li>
<li>$ ： 匹配字符串的介绍</li>
<li>{n} ： 重复 n 次</li>
<li>{n,} ： 重复 n 次或更多次</li>
<li>[c] ： 匹配单个字符 c</li>
<li>[a-z] ： 匹配 a-z 小写字母的任意一个</li>
</ul>
<p>小括号()之间匹配的内容，可以在后面通过$1来引用，$2 表示的是前面第二个()里的内容。正则里面容易让人困惑的是\转义特殊字符。</p>
<p>2.4 rewrite 实例<br>例 1：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">http &#123;</span><br><span class="line">    # 定义image日志格式</span><br><span class="line">    log_format imagelog &apos;[$time_local] &apos; $image_file &apos; &apos; $image_type &apos; &apos; $body_bytes_sent &apos; &apos; $status;</span><br><span class="line">    # 开启重写日志</span><br><span class="line">    rewrite_log on;</span><br><span class="line">    server &#123;</span><br><span class="line">        root /home/www;</span><br><span class="line">        location / &#123;</span><br><span class="line">                # 重写规则信息</span><br><span class="line">                error_log logs/rewrite.log notice;</span><br><span class="line">                # 注意这里要用‘’单引号引起来，避免&#123;&#125;</span><br><span class="line">                rewrite &apos;^/images/([a-z]&#123;2&#125;)/([a-z0-9]&#123;5&#125;)/(.*)\.(png|jpg|gif)$&apos; /data?file=$3.$4;</span><br><span class="line">                # 注意不能在上面这条规则后面加上“last”参数，否则下面的set指令不会执行</span><br><span class="line">                set $image_file $3;</span><br><span class="line">                set $image_type $4;</span><br><span class="line">        &#125;</span><br><span class="line">        location /data &#123;</span><br><span class="line">                # 指定针对图片的日志格式，来分析图片类型和大小</span><br><span class="line">                access_log logs/images.log mian;</span><br><span class="line">                root /data/images;</span><br><span class="line">                # 应用前面定义的变量。判断首先文件在不在，不在再判断目录在不在，如果还不在就跳转到最后一个url里</span><br><span class="line">                try_files /$arg_file /image404.html;</span><br><span class="line">        &#125;</span><br><span class="line">        location = /image404.html &#123;</span><br><span class="line">                # 图片不存在返回特定的信息</span><br><span class="line">                return 404 &quot;image not found\n&quot;;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对形如<code>/images/ef/uh7b3/test.png</code>的请求，重写到<code>/data?file=test.png</code>，于是匹配到<code>location /data</code>，先看<code>/data/images/test.png</code>文件存不存在，如果存在则正常响应，如果不存在则重写 tryfiles 到新的 image404 location，直接返回 404 状态码。</p>
<p>例 2：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&amp;height=$3? last;</span><br></pre></td></tr></table></figure>

<p>对形如<code>/images/bla_500x400.jpg</code>的文件请求，重写到<code>/resizer/bla.jpg?width=500&amp;height=400</code>地址，并会继续尝试匹配 location。</p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><p><a href="http://www.nginx.cn/216.html" target="_blank" rel="noopener">http://www.nginx.cn/216.html</a><br><a href="http://www.ttlsa.com/nginx/nginx-rewriting-rules-guide/" target="_blank" rel="noopener">http://www.ttlsa.com/nginx/nginx-rewriting-rules-guide/</a><br>老僧系列 nginx 之 rewrite 规则快速上手<br><a href="http://fantefei.blog.51cto.com/2229719/919431" target="_blank" rel="noopener">http://fantefei.blog.51cto.com/2229719/919431</a></p>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/nginx/" rel="tag"># nginx</a>
            
              <a href="/tags/配置/" rel="tag"># 配置</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/thank2017.html" rel="next" title="2017年度总结">
                  <i class="fa fa-chevron-left"></i> 2017年度总结
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/html-input-file-xls.html" rel="prev" title="html input="file" 浏览时只显示指定文件类型 xls、xlsx、csv[转]">
                  html input="file" 浏览时只显示指定文件类型 xls、xlsx、csv[转] <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    
  <div class="comments" id="comments">
    <div id="disqus_thread">
      <noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
    </div>
  </div>
  
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">

          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/logo.png"
      alt="dctxf">
  <p class="site-author-name" itemprop="name">dctxf</p>
  <div class="site-description motion-element" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">57</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">categories</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">tags</span>
        </a>
      </div>
    
  </nav>
  <div class="feed-link motion-element">
    <a href="/rss.xml" rel="alternate">
      <i class="fa fa-rss"></i>RSS
    </a>
  </div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/dctxf" title="GitHub &rarr; https://github.com/dctxf" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="/" title="Weibo &rarr; "><i class="fa fa-fw fa-globe"></i>Weibo</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="/dctxf" title="Twitter &rarr; dctxf"><i class="fa fa-fw fa-globe"></i>Twitter</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="/dctxf" title="FB Page &rarr; dctxf"><i class="fa fa-fw fa-globe"></i>FB Page</a>
      </span>
    
  </div>


  <div class="links-of-blogroll motion-element links-of-blogroll-block">
    <div class="links-of-blogroll-title">
      <i class="fa  fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://iwuly.com/" title="http://iwuly.com/" rel="noopener" target="_blank">iwuly</a>
        </li>
      
        <li class="links-of-blogroll-item">
          <a href="http://mybulesea.github.io/" title="http://mybulesea.github.io/" rel="noopener" target="_blank">深蓝</a>
        </li>
      
        <li class="links-of-blogroll-item">
          <a href="http://chayangge.com/" title="http://chayangge.com/" rel="noopener" target="_blank">插秧哥</a>
        </li>
      
    </ul>
  </div>

        </div>
      </div>
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-location-正则写法"><span class="nav-number">1.</span> <span class="nav-text">1. location 正则写法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实际使用建议"><span class="nav-number">1.1.</span> <span class="nav-text">实际使用建议</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-Rewrite-规则"><span class="nav-number">2.</span> <span class="nav-text">2. Rewrite 规则</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-flag-标志位"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 flag 标志位</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-if-指令与全局变量"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 if 指令与全局变量</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#if-判断指令"><span class="nav-number">2.2.1.</span> <span class="nav-text">if 判断指令</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-常用正则"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 常用正则</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">3.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">dctxf</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> v3.9.0</div>

        








        
      </div>
    </footer>

    

  </div>

  
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

<script src="/js/utils.js?v=7.3.0"></script>
  <script src="/js/motion.js?v=7.3.0"></script>


  <script src="/js/affix.js?v=7.3.0"></script>
  <script src="/js/schemes/pisces.js?v=7.3.0"></script>



<script src="/js/next-boot.js?v=7.3.0"></script>




  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>















  <script src="/js/local-search.js?v=7.3.0"></script>














  

  

  


  
  <script src="/js/scrollspy.js?v=7.3.0"></script>
<script src="/js/post-details.js?v=7.3.0"></script>


    
<script>
  function loadCount() {
    var d = document, s = d.createElement('script');
    s.src = 'https://dctxf.disqus.com/count.js';
    s.id = 'dsq-count-scr';
    (d.head || d.body).appendChild(s);
  }
  // defer loading until the whole page loading is completed
  window.addEventListener('load', loadCount, false);
</script>
<script>
  var disqus_config = function() {
    this.page.url = "https://dctxf.com/nginx-regex.html";
    this.page.identifier = "nginx-regex.html";
    this.page.title = 'nginx配置location总结及rewrite规则写法[转载]';};
  function loadComments() {
    if (window.DISQUS) {
      DISQUS.reset({
        reload: true,
        config: disqus_config
      });
    } else {
      var d = document, s = d.createElement('script');
      s.src = 'https://dctxf.disqus.com/embed.js';
      s.setAttribute('data-timestamp', '' + +new Date());
      (d.head || d.body).appendChild(s);
    }
  }
    $(function() {
      var offsetTop = $('#comments').offset().top - $(window).height();
      if (offsetTop <= 0) {
        // load directly when there's no a scrollbar
        window.addEventListener('load', loadComments, false);
      } else {
        $(window).on('scroll.disqus_scroll', function() {
          // offsetTop may changes because of manually resizing browser window or lazy loading images.
          var offsetTop = $('#comments').offset().top - $(window).height();
          var scrollTop = $(window).scrollTop();

          // pre-load comments a bit? (margin or anything else)
          if (offsetTop - scrollTop < 60) {
            $(window).off('.disqus_scroll');
            loadComments();
          }
        });
      }
    });
  
</script>

</body>
</html>
